/*
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package cn.kuaipan.android.openapi.tasks;

import java.io.File;

import com.easyfun.healthmagicbox.comm.PicturesUploadTask;
import com.easyfun.healthmagicbox.util.SharedPreferencesUtil;
import com.easyfun.healthmagicbox.util.URIConverter;

import cn.kuaipan.android.openapi.KuaipanAPI;
import cn.kuaipan.android.openapi.RequestBase;
import cn.kuaipan.android.openapi.ResultBase;
import cn.kuaipan.android.openapi.TransportListener;
import cn.kuaipan.android.sdk.exception.KscException;
import cn.kuaipan.android.sdk.exception.KscRuntimeException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class UploadTask {

	private static final String TAG = "UploadTask";

	private ProgressDialog dialog;
	private Activity activity;

	private String personID;
	private Context context;
    private PicturesUploadTask picUpTask ;
    
	public UploadTask(PicturesUploadTask picUpTask) {
		this.picUpTask = picUpTask;
		personID = picUpTask.getPersonID();
		context = picUpTask.getContext();
	}

	public UploadTask(String personID, Context context) {
		this.personID = personID;
		this.context = context;
	}
	// public void showProgressDialog() {
	// dialog = new ProgressDialog(activity);
	// dialog.setMessage(activity.getString(R.string.uploading));
	// dialog.setCancelable(false);
	// dialog.show();
	// }

	// public void hideProgressDialog() {
	// if (dialog != null && dialog.isShowing()) {
	// dialog.dismiss();
	// }
	// }

	// protected void displayAlert(String title, String message) {
	//
	// AlertDialog.Builder confirm = new AlertDialog.Builder(activity);
	// confirm.setTitle(title);
	// confirm.setMessage(message);
	//
	// confirm.setNegativeButton(activity.getString(R.string.ok),
	// new DialogInterface.OnClickListener() {
	//
	// public void onClick(DialogInterface dialog, int which) {
	//
	// dialog.dismiss();
	// }
	// });
	//
	// confirm.show().show();
	// }

	// protected void displayErrorAlert(String title, String message) {
	//
	// AlertDialog.Builder confirm = new AlertDialog.Builder(activity);
	// confirm.setTitle(title);
	// confirm.setMessage(message);
	//
	// confirm.setNegativeButton(activity.getString(R.string.ok),
	// new DialogInterface.OnClickListener() {
	//
	// public void onClick(DialogInterface dialog, int which) {
	//
	// activity.finish();
	// }
	// });
	//
	// confirm.show().show();
	// }

	public void start(RequestBase req) {
		new Upload().execute(req);
	}

	private class Upload extends MyAsyncTask<RequestBase, Void, ResultBase> {


		protected void onPreExecute() {
			Log.v(TAG, "====Upload task onPreExecute====");
			// showProgressDialog();
		}

		protected ResultBase doInBackground(RequestBase param) {
			Log.v(TAG, "====Upload task doInBackground====");
//			if (params == null || params.length != 1) {
//				return null;
//			}

			final RequestBase req = param;
			//final Uri selectedImage = req.getFileUri();
			final KuaipanAPI api = req.getApi();

//			String[] filePathColumn = { MediaStore.Images.Media.DATA };
//
//			Cursor cursor = activity.getContentResolver().query(selectedImage,
//					filePathColumn, null, null, null);

			// if (cursor != null) {
			// cursor.moveToFirst();
			// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			// String filePath = cursor.getString(columnIndex);
			// cursor.close();
			//
			ResultBase result = new ResultBase();

			String fileName= req.getFilePath();
			
			String localPath = URIConverter.getFilePathFromAppSDCard(context,fileName);
			result.setRemotePath(personID+"/"+fileName);
			result.setFilePath(localPath);
			
			File file = new java.io.File(localPath);
			if (!file.exists()) {
				return null;
			}
			
			Log.v(TAG, "ready to upload file " + file.getAbsolutePath()
					+ " name:" + file.getName());
			
			Boolean folderexist = SharedPreferencesUtil.getInstance(context)
					.getKingDisk(personID);
			if (!folderexist)
			{				
				try {					
					api.mkdirs(personID);
					SharedPreferencesUtil.getInstance(context)
						.setKingDisk(personID);
				} catch (KscRuntimeException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (KscException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
			
			try {
				api.upload(file, "/" +result.getRemotePath(), new TransportListener(
						TransportListener.OPERATION_UPLOAD, "Upload"));
			} catch (KscRuntimeException e) {
				e.printStackTrace();
				result.setErrorMsg(e.getMessage());
			} catch (KscException e) {
				e.printStackTrace();
				result.setErrorMsg(e.getMessage());
			} catch (InterruptedException e) {
				e.printStackTrace();
				result.setErrorMsg(e.getMessage());
			}

			Log.v(TAG, "====Upload task doInBackground end====");
			return result;
			// }
			// return null;
		}

		protected void onPostExecute(ResultBase result) {
			// hideProgressDialog ();
			if (result == null) {
//				Looper.prepare();
//				Toast.makeText(activity,
//						"Please, select photo from gallery app",
//						Toast.LENGTH_LONG).show();
				return;
			}

			if (result.getErrorMsg() != null) {
				if (picUpTask != null)
				{
					//set to failed, this task will be rerun in next loop
					picUpTask.failedRun(picUpTask);
				}
				// displayErrorAlert(
				// activity.getString(R.string.upload_failure_title),
				// result.getErrorMsg());
				
			} else {
				// displayAlert("Upload Task Finish",
				// "Upload file [" + result.getFilePath()
				// + "] Successed!");
				if (picUpTask != null)
				{
					picUpTask.successfulRun(picUpTask);
				}
			}
		}
	}
}
